<template>
  <div class="box">
    <div class="user-login">
      <el-input
        placeholder="请输入账号"
        v-model="phoneNumber"
        maxlength="11"
        class="phone-num"
      ></el-input>
      <!-- 
      <el-select
        style="width: 21rem; height: 4.2rem"
        v-model="phoneNumber"
        filterable
        placeholder="请选择账号"
      >
        <el-option
          style="width: 21rem; height: 2.2rem; font-size: 1.2rem"
          v-for="(item, index) in peoplePhone"
          :key="index"
          :label="item"
          :value="item"
        >
        </el-option>
      </el-select> -->
      <el-input
        placeholder="请输入密码"
        v-model="password"
        type="text"
        maxlength="28"
        class="phone-password"
      ></el-input>
      <div class="remeberBox">
        <el-checkbox v-model="remeber">记住密码</el-checkbox>
      </div>
      <el-button class="user-login-btn" @click="handleLogin">登录</el-button>
    </div>
  </div>
</template>
<!-- <script src="../../../public/debug/log4javascript.js"></script>  -->
<!-- <script src="https://cdn.bootcdn.net/ajax/libs/log4javascript/1.4.9/log4javascript.js"></script>  -->

<script>
import { genTestUserSig } from "../../../public/debug/GenerateTestUserSig";
//import router from "../../router/index"
import { getUserInfoDetails } from "../../api/index";
import { mapMutations, mapState } from "vuex";
import mp3 from "../../assets/music/login.wav";
const Base64 = require("js-base64").Base64;
var liginLogTimer = null;
export default {
  name: "Login",
  data() {
    return {
      loginlogList: "", //登录页的日志数据
      reLoginTimer: null, //重新登陆计时器
      remeber: false, //是否记住密码
      UserID: "",
      verifyCode: "",
      disableFetchCodeBtn: false,
      phoneNumber: "", //账号
      password: "", //密码
      appAnswerMusic:null
    };
  },
  created(){
    this.appAnswerMusic = null;
    this.appAnswerMusic = new Audio();
    this.appAnswerMusic.src = mp3;
  },
  mounted() {
    console.log(localStorage.getItem("phoneNumber"),localStorage.getItem("phoneNumber"))
    // 如果用户名存储在本地，则进入页面会进行自动登录
    let phoneNumber = localStorage.getItem("phoneNumber");
    if (phoneNumber) {
      this.phoneNumber = localStorage.getItem("phoneNumber");
      this.password = Base64.decode(localStorage.getItem("password")); // base64解密
      this.remeber = true;
      localStorage.setItem("remeber", true);
      // this.handleLogin();
    } else {
      this.phoneNumber = "";
      this.password = "";
    }
  },
  computed: {
    ...mapState({
      isLogin: (state) => state.isLogin, //用户登录状态
      //loginlogList:(state) => state.loginlogList,//日志内容
    }),
  },
  methods: {
    ...mapMutations([
      "setcurrentUserId",
      "setUserInfoDetails",
      "setLoginlogList",
      //  将this.setcurrentUserId 映射为 this.$store.commit("setcurrentUserId")
    ]),
    refreshLog() {
      clearInterval(liginLogTimer);
      liginLogTimer = null;
      console.log("-------------------清空----------------------");
      liginLogTimer = setInterval(() => {
        console.log('日志下载的计时器',111)
        // let refreshHours = new Date().getHours();
        let refreshMin = new Date().getMinutes();
        let refreshSec = new Date().getSeconds();
        if (refreshMin == "00" && refreshSec == "00") {
          // 指定每天凌晨做的事情
          // let date = new Date().Format("yyyy-MM-dd-hh");
          if (this.loginlogList) {
            // this.log.info("整点下载日志");
            this.loginlogList +=
              new Date().Format("yyyy-MM-dd hh:mm:ss") +
              "  info - 整点下载日志\n";
            // this.download(date + "-1", this.loginlogList);
          }
          console.log("当前的日志数据", this.loginlogList);
          this.loginlogList = "";
        }
      }, 1000);
    },
    // download(filename, text) {
    //   var element = document.createElement("a");
    //   element.setAttribute(
    //     "href",
    //     "data:text/plain;charset=utf-8," + encodeURIComponent(text) //encodeURIComponent(text)
    //   );
    //   element.setAttribute("download", filename);
    //   //element.href = "D:";
    //   element.style.display = "none";
    //   document.body.appendChild(element);

    //   element.click();
    //   document.body.removeChild(element);
    // },
    handleLogin: async function () {
      if (!this.phoneNumber) {
        this.$message.error("请输入账号");
        return;
      }
      if (!this.password) {
        this.$message.error("请输入密码");
        return;
      }
      const params = {
        tyid: this.phoneNumber,
        password: this.password
      };
      // http://192.168.253.217:6016/api/UserInfo/GetUserId?PhoneNum=15737973871
      await getUserInfoDetails(params)
        .then((res) => {
          // this.log = log4javascript.getDefaultLogger();
          //获取的日志记录器将忽略所有日志记录请求，不会输出任何日志信息
          // this.log = log4javascript.getNullLogger()
          if (res.code == 0) {
            clearInterval(this.reLoginTimer);
            this.reLoginTimer = null;
            if (this.remeber) {
              //如果选中了记住密码,存储密码
              let password = Base64.encode(this.password); // base64加密
              localStorage.setItem("phoneNumber", this.phoneNumber);
              localStorage.setItem("password", password);
              localStorage.setItem("remeber", true);
              console.log('remeber',localStorage.getItem("remeber"))
              console.log('phoneNumber',localStorage.getItem("phoneNumber"))
              console.log('password',localStorage.getItem("password"))
            } else {
              localStorage.removeItem("phoneNumber");
              localStorage.removeItem("password");
              localStorage.setItem("remeber", false);
            }
            //更改登陆状态
            this.$store.commit("userLoginSuccess");
            //存储用户信息
            //this.$store.commit("setUserInfoDetails", { ...res });
            this.setUserInfoDetails({ ...res });
            //记录当前登录人的用户id
            this.setcurrentUserId(res.residents[0].rsid);
            //存储token
            window.localStorage["token"] = JSON.stringify(res.token);
            //存储token过期时间
            window.localStorage["expiration"] = JSON.stringify(res.expiration);
            //登录TRTCCalling
            console.log(
              "***********************登录的TRTC电话**********************"
            );
            //const userSig = genTestUserSig(res.residents[0].rsid).userSig;
            // UserSig 是用户登录即时通信 IM 的密码，其本质是对 UserID 等信息加密后得到的密文
            const userSig = genTestUserSig(res.account.tel.toString()).userSig;
            this.$store.commit("setLoginUserInfo", {
              userId: res.account.tel,
              userSig,
            });
            // let date = new Date().Format("yyyy-MM-dd-hh");
            //登录失败过，该字段才会有数据。登陆成功时下载一下日志
            if (this.loginlogList) {
              clearInterval(liginLogTimer);
              liginLogTimer = null;
              // this.log.info("登陆成功下载日志");
              this.loginlogList +=
              new Date().Format("yyyy-MM-dd hh:mm:ss") +
              "  info - 登陆成功下载日志\n";
              // this.download(date + "-1", this.loginlogList);
            }else{
              clearInterval(liginLogTimer);
              liginLogTimer = null;
            }
            this.loginlogList = "";
            // 播放登录成功提示音
            this.appAnswerMusic.play();
            console.log('播放登录成功提示音-----------------------');

            // this.log.info("登录成功");
            this.loginlogList += new Date().Format("yyyy-MM-dd hh:mm:ss") + "  info - 登录成功\n";
            let newlog = this.loginlogList;
            this.$store.commit("setLoginLogList", newlog);
            //const userSig = genTestUserSig('18800000002').userSig;
            this.$trtcCalling.login({
              userID: res.account.tel, //res.residents[0].rsid,//res.account.tel,
              userSig,
            });
          } else {
            this.$message.error(res.error_msg);
            //标记一下
            if (this.phoneNumber && this.password) {
              clearInterval(this.reLoginTimer);
              this.reLoginTimer = null;
              this.reLoginTimer = setInterval(() => {
                console.log(
                  "=====================重新登陆======================",
                  this.isLogin
                );
                //如果当前是未登录成功状态，才允许重新登录
                if (this.isLogin == false) {
                  // this.log.error(res.error_msg+"，尝试重新登录");
                  this.loginlogList +=
                    new Date().Format("yyyy-MM-dd hh:mm:ss") +
                    "  error - "+res.error_msg+"，尝试重新登录\n";
                  this.handleLogin(); //登陆失败，重新登陆
                  this.refreshLog();
                }
              }, 10 * 1000);
            }
          }
        })
        .catch((err) => {
          //this.log = log4javascript.getDefaultLogger();
          //获取的日志记录器将忽略所有日志记录请求，不会输出任何日志信息
          console.log("登录接口发生错误", err);
          // this.log = log4javascript.getNullLogger()
          //标记一下
          if (this.phoneNumber && this.password) {
            clearInterval(this.reLoginTimer);
            this.reLoginTimer = null;
            this.reLoginTimer = setInterval(() => {
              console.log(
                "=====================重新登陆======================",
                this.isLogin
              );
              //如果当前是未登录成功状态，才允许重新登录
              if (this.isLogin == false) {
                // this.log.error("登录接口发生错误："+err+",正在重新登录");
                this.loginlogList +=
                    new Date().Format("yyyy-MM-dd hh:mm:ss") +
                    `  error - 登录接口发生错误：${
                      err}，正在重新登录`+"\n";
                this.handleLogin(); //登陆失败，重新登陆
                this.refreshLog();
              }
            }, 10 * 1000);
          }
        });
    },
  },
};
</script>

<style scoped>
.box {
  margin: 0;
  background-repeat: no-repeat;
  background-size: cover;
  background-image: url("../../assets/images/background.jpg");
  height: 100%;
}
.el-select /deep/ .el-input__inner {
  height: 3.2rem;
  border-radius: 0.3rem;
  font-size: 1.2rem;
  margin-left: 0rem;
  padding-left: 0rem 0.9rem;
}
.el-input /deep/ .el-input__inner {
  -webkit-appearance: none;
  background-color: #fff;
  background-image: none;
  border-radius: 0.25rem;
  border: 1px solid #dcdfe6;
  box-sizing: border-box;
  color: #606266;
  display: inline-block;
  font-size: 1.6rem;
  height: 4.2rem;
  line-height: 4.2rem;
  outline: 0;
  padding: 0 1rem;
  transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
  width: 100%;
}
.user-login {
  font-size: 2rem;
  width: 21rem;
  margin: 0 auto;
  padding-top: 17rem;
}
.phone-num {
  width: 27rem;
  height: 5rem;
  margin-bottom: 0.3rem;
}
.phone-password {
  width: 27rem;
  height: 5rem;
  margin-bottom: 0.3rem;
}
.phone-password /deep/ .el-input__inner {
  -webkit-text-security: disc !important;
}
.user-login-btn {
  margin-top: 0.2rem;
  width: 27rem;
  height: 4rem;
  font-size: 1.6rem;
  border-radius: 0.3rem;
}
/* @media screen and (max-width: 767px) {
  .user-login {
    font-size: 16px;
    width: 90%;
    min-width: 300px;
    margin: 0 auto;
    padding-top: 50px;
  }
} */
.remeberBox {
  margin-top: -1.3rem;
  /* background-color: red; */
  text-align: left;
  color: white;
}
.remeberBox .el-checkbox {
  color: white;
}
.el-checkbox /deep/ .el-checkbox__inner {
  width: 1.4rem;
  height: 1.4rem;
}
.el-checkbox /deep/ .el-checkbox__inner::after {
  height: 0.9rem;
  width: 0.5rem;
  position: absolute;
  left: 0.3rem;
  top: 0rem;
  transition: transform 0.15s ease-in 0.05s;
  transform-origin: center;
}
.el-checkbox /deep/ .el-checkbox__label {
  font-size: 1rem;
}
</style>
